package se.boliang.Q02;

import java.util.Stack;

public class StackWithMinFunc {

	/**
	 * We use two stacks
	 * 'commonStack' is normal used as a common stack
	 * 'auxiliaryStack' is associated with 'commonStack', the minimum value is stored on the top of this stack.
	 * when a new value push in the common stack, after then, comparing the top value with the new input value.
	 */
	private Stack<Integer> commonStack = new Stack<Integer>(); 
	private Stack<Integer> auxiliaryStack = new Stack<Integer>();
	private int tempMinValue; 
	
	public int min() {
		return auxiliaryStack.pop(); 
	}
	
	public void push(int value) {
 		commonStack.push(value);  
		
 		/**
 		 * We should us a temporary variable 'tempMinValue' to compare with the input value
 		 * if the input value is smaller, then we push input value into auxiliary stack
 		 * and copy the minimum value to 'tempMinValue'
 		 * else if the input value is greater than 'tempMinValue', we still continue push the 'tempMinValue'
 		 * into the auxiliary stack
 		 */
		if (auxiliaryStack.isEmpty() || value < tempMinValue) {
			auxiliaryStack.push(value); 
			tempMinValue = value; 
		} else {
			auxiliaryStack.push(tempMinValue); 
		}
	}
}
